import { onShow } from '@dcloudio/uni-app'
import { watch } from 'vue'
import { useCartStore } from '../stores/cart'
import { useUserStore } from '../stores/user'
import Dialog from '/wxcomponents/vant/dialog/dialog';

export const useFormat = () => {
	// 价格格式化
	const formatPrice = (price : number) => {
		return price.toFixed(2)
	}

	return {
		formatPrice
	}
}

// 设置每个页面tabBar的徽标
export const useTabBarBadge = () => {
	const store = useCartStore()
	onShow(() => {
		setTabBarBadge()
	})
	watch(() => store.allGoodsNum, () => {
		setTabBarBadge()
	})

	const setTabBarBadge = () => {
		if (store.allGoodsNum) {
			uni.setTabBarBadge({
				index: 2,
				text: store.allGoodsNum + ''
			})
		} else {
			uni.removeTabBarBadge({
				index: 2
			})
		}
	}
}

// token非空校验
export const useIsToken = () => {
	onShow(() => {
		const store = useUserStore()
		if (!store.token) {
			Dialog.alert({
				title: '提示',
				message: '未登录，请点击跳转登录页',
			}).then(() => {
				uni.redirectTo({
					url: '/subpkg/login/login'
				})
			});
		}
	})
}

// 设置tabBar文字
export const useSetTabBarItem = () => {
	onShow(() => {
		const store = useUserStore()
		if (!store.token) {
			return uni.setTabBarItem({
				index: 3,
				text: '未登录'
			})
		} else {
			return uni.setTabBarItem({
				index: 3,
				text: '我的'
			})
		}
	})
}